package cn.study.zgm.nettyall.selector.thread;

import cn.study.zgm.nettyall.channel.ByteBufferUtil;
import jdk.internal.dynalink.beans.StaticClass;
import lombok.SneakyThrows;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * packageName cn.study.zgm.nettyall.selector.thread
 *
 * @author 你的名字
 * @version JDK 8
 * @className Server (此处以class为例)
 * @date 2025/2/27
 * @description TODO
 */
public class Server {
    public static void main(String[] args) throws IOException {
        // 创建服务器端
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress("127.0.0.1",8081));
        ssc.configureBlocking(false);

        // 注册到selector中去
        final Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT,null);

        while (true){
            selector.select();
            final Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                final SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()){
                    final ServerSocketChannel ssChannel = (ServerSocketChannel)key.channel();
                    final SocketChannel sChannel = ssChannel.accept();
                    sChannel.configureBlocking(false);
                    // 注册
                    Worker worker = new Worker("工作");
                    worker.register(sChannel);
                }

            }
        }
    }

    static class Worker implements Runnable {
        private Thread thread;
        private Selector selector;
        private ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();
        private String name;
        private volatile boolean start =false;

        public Worker(String name){
            this.name = name;

        }
        public void register(SocketChannel sChannel) throws IOException {
            if (!start){
                start = true;
                this.selector = Selector.open();
                Thread thread = new Thread(this,name);
                thread.start();
                System.out.println("线程开始运行了 ");
            }
//            sChannel.register(selector,SelectionKey.OP_WRITE,null);
            queue.add(()->{
                try {
                    sChannel.register(selector,SelectionKey.OP_READ,null);
                } catch (ClosedChannelException e) {
                    e.printStackTrace();
                }
            });
            selector.wakeup();
        }

        @SneakyThrows
        @Override
        public void run() {
            while (true){
                try {
                    selector.select();
                    final Runnable task = queue.poll();
                    if (task!= null){
                        queue.poll().run();
                    }

                    final Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()){
                        final SelectionKey next = iterator.next();
                        iterator.remove();
                        System.out.println("打印key:"+next);
                        if (next.isReadable()){
                            SocketChannel channel = (SocketChannel) next.channel();
                            final ByteBuffer buffer = ByteBuffer.allocate(32);
                            channel.read(buffer);
                            buffer.flip();
                            ByteBufferUtil.debugAll(buffer);
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}
